package com.will.seed.websocket;


import java.net.InetSocketAddress;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

/**
 * Created by xiaoEight on 2018/8/17.
 */
public class WebSocketServer {

    private final WebSocketServerInitializer webSocketServerInitializer;
    private final ChannelGroup channelGroup;
    private final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private final EventLoopGroup workGroup = new NioEventLoopGroup();
    private Channel channel;
    private final InetSocketAddress address;

    public WebSocketServer(ChannelGroup channelGroup,
                           WebSocketServerInitializer webSocketServerInitializer,
                           InetSocketAddress address){
        this.channelGroup = channelGroup;
        this.webSocketServerInitializer = webSocketServerInitializer;
        this.address = address;
    }

    public ChannelFuture start() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(webSocketServerInitializer)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture future = bootstrap.bind(address).syncUninterruptibly();
        channel = future.channel();
        return future;
    }

    public void destroy() {
        if(channel != null) {
            channel.close();
        }

        channelGroup.close();
        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
        WebSocketServerInitializer webSocketServerInitializer = new WebSocketServerInitializer(channelGroup);
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9090);

        WebSocketServer server = new WebSocketServer(channelGroup,
                webSocketServerInitializer,
                address);
        ChannelFuture future = server.start();
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                server.destroy();
            }
        });

        future.channel().closeFuture().syncUninterruptibly();
    }
}
